package com.i18n.filter;


import com.i18n.utils.MessageUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Locale;

/**
 * @author WuLiangHang
 */
@WebFilter("/*")
public class MessageFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String l = request.getParameter("request_locale");
        Locale locale = null;
        if (l != null && !l.isEmpty()) {
            String[] strs = l.split("_");
            locale = new Locale(strs[0], strs[1]);
            request.getSession().setAttribute("i18nLocale", locale);
        } else {
            locale = (Locale) request.getSession().getAttribute("i18nLocale");
        }
        if (locale == null){
            locale = new Locale("zh","CN");
            request.getSession().setAttribute("i18nLocale", locale);
        }
        MessageUtils.setLocale(locale);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
